import { fakeRegister, getCaptcha, step1Validate, addUserInfo, resetPassword } from '../services/login';

export default {
  namespace: 'register',

  state: {
    status: undefined,
  },

  effects: {
    *getCaptcha({ payload }, { call, put }) {
      yield call(getCaptcha, payload);
    },
    *step1Validate({ payload, callback }, { call, put }) {
      const response = yield call(step1Validate, payload);
      if (response) {
        yield put({
          type: 'setInfo',
          payload,
        });
        if (callback) callback();
      }
    },
    *step2Validate({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'setInfo',
        payload,
      });
      const account = yield select(state => state.register.account);
      const { info } = payload;
      const userInfo = { ...account, ...info };
      userInfo.status = 'Unauth';
      userInfo.mobile = userInfo.userName;
      userInfo.tel = userInfo.mobile;

      userInfo.province = userInfo.areaData[0];
      userInfo.city = userInfo.areaData[1];
      userInfo.area = userInfo.areaData[2];

      delete userInfo.areaData;

      const response = yield call(fakeRegister, userInfo);
      if (response) {
        yield put({
          type: 'clean',
        });
        if (callback) callback();
      }
    },
    *resetPassword({ payload, callback }, { call, put }) {
      const response = yield call(resetPassword, payload);
      if (response) {
        yield put({
          type: 'setInfo',
          payload,
        });
        if (callback) callback();
      }
    },
  },

  reducers: {
    setInfo(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    clean(state, {}) {
      return {
        ...state,
        info: null,
        account: null,
      };
    },
  },
};
